package jacker.bit.price;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Vibrator;

public class PriceChecker {
	
	public static List<Platform> getPlatforms(){
		List<Platform> platforms = new ArrayList<Platform>();
		platforms.add(new PlatformMtgox());
		platforms.add(new PlatformBitstamp());
		platforms.add(new PlatformBtce());
		platforms.add(new Platform796());
		platforms.add(new PlatformBtcchina());
		platforms.add(new PlatformHuobi());
		platforms.add(new PlatformBtctrade());
		platforms.add(new PlatformCnbtc());
		platforms.add(new PlatformFxbtc());
		platforms.add(new PlatformOkcoin());
		platforms.add(new PlatformBtc100());
		return platforms;
	}
	
	public static Platform getPlatform(List<Platform> list,String code){
		for(Platform p:list){
			if(p.getCode()!=null && p.getCode().equals(code))
				return p;
		}
		return null;
	}
	
	
	public static boolean checkPrices(final Context ctx){
		
		List<CurrentPrice> cps = new PriceHelper(ctx).getCurrentPrices();
		List<Platform> platforms = getPlatforms();
		
		for(CurrentPrice cp:cps){
			UtilLog.d("thread: "+cp.getThreadid());
			try{
				Platform p = getPlatform(platforms,cp.getThreadid());
				cp.setCurrency(p.getCurrency());
				cp.setThreadname(p.getName(ctx));
				matchPrice(ctx,p.getPrice(),cp);
			}catch(Exception e){
				UtilLog.e(e);
			}
		}
		
		PriceHelper.hideProgress();
        
		return true;
	}
	
	private static void matchPrice(final Context ctx,float price,CurrentPrice cp){
		
		float up = PrefStore.getUppercent(ctx); // up percent
		float down = PrefStore.getDownpercent(ctx);
		
		PriceHelper ph = new PriceHelper(ctx);
		
		cp.setPrice(price);
		
		Price p = new Price();
		p.setThreadid(cp.getThreadid());
		p.setPrice(price);
		p.setCurrency(cp.getCurrency());
		
		UtilLog.i(cp.getOrigprice()+" : "+price);
		
		if( (price - cp.origprice)>=up*0.01f*cp.origprice ){
			cp.origprice = price;
			cp.maxprice = price;
			cp.minprice = price;
			ph.updateCurrentPrice(cp);
			
			p.setAlarm(1);
			ph.insertPrice(p);
			
			if(price>0.0f)
			 notifyNewMessage(cp,ctx,true);
			
		}else if( (cp.origprice - price)>=down*0.01f*price){
			cp.origprice = price;
			cp.maxprice = price;
			cp.minprice = price;
			ph.updateCurrentPrice(cp);
			
			p.setAlarm(-1);
			ph.insertPrice(p);
			
			if(price>0.0f)
				notifyNewMessage(cp,ctx,false);
			
		}else{
			if(price>cp.maxprice)
				cp.maxprice = price;
			
			if(price<cp.minprice)
				cp.minprice = price;
			
			ph.updateCurrentPrice(cp);
			
			//p.setAlarm(0);
			//ph.insertPrice(p);
		}
		
		
	}
	
	
	
	public static String httpGet(String urlstr) throws Exception{
		UtilLog.d(urlstr);
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter("http.socket.timeout",20000);
		HttpGet get = new HttpGet(urlstr);
		HttpResponse res = httpclient.execute(get);
		int status = res.getStatusLine().getStatusCode();
		if(status == 200){
			String result = EntityUtils.toString(res.getEntity());
			UtilLog.d(result);
			return result;
		}else{
			throw new IOException("Error statuscode: "+status);
		}
		
		
	}
	
	public static String httpGetLimit(String urlstr) throws Exception{
		URL url = new URL(urlstr);
		java.io.InputStream is = url.openStream();
		byte[] bytes = new byte[128];
		is.read(bytes);
		is.close();
		return new String(bytes,"UTF-8");
	}
		
	private static void notifyNewMessage(CurrentPrice m,Context ctx,boolean up){

			UtilLog.d( m.getThreadid());
			Intent intent = new Intent(ctx, ActivityPrices.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_CLEAR_TOP);
			//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
			PendingIntent pintent = PendingIntent.getActivity(ctx, 0, intent, 0);

			String nsubject = m.getThreadname()	+ " : "	+ m.getCurrency()+ UtilString.price(m.getPrice());
			// the next two lines initialize the Notification, using the configurations above
			Notification notification = 
				new Notification(up?R.drawable.up_arrow:R.drawable.down_arrow, nsubject , System.currentTimeMillis());
			notification.setLatestEventInfo(ctx, ctx.getString(R.string.notification_new_title)
					, nsubject, pintent);
			
			notification.ledARGB = up?0x00FF00:0xFF0000;
			notification.ledOnMS = 1000;
			notification.ledOffMS = 1000;
			notification.flags = Notification.FLAG_AUTO_CANCEL|Notification.FLAG_SHOW_LIGHTS;//
			
			NotificationManager nm = (NotificationManager) ctx
				.getSystemService(Context.NOTIFICATION_SERVICE);
			nm.notify(100, notification);	
		
		if(PrefStore.isPriceVibrate(ctx)){
			vibrate(ctx);
		}
		
		String ringtone = PrefStore.getUpRing(ctx);
		if(!up){
			ringtone = PrefStore.getDownRing(ctx);
		}
		
		if(ringtone!=null && ringtone.length()>0){
			try{
				Ringtone ring = RingtoneManager.getRingtone(ctx, Uri.parse(ringtone));
				ring.setStreamType(AudioManager.STREAM_NOTIFICATION);
				ring.play();
			}catch(Throwable e){
				UtilLog.e("ring: "+e.getMessage());
			}
		}
		
		
	}
	
	public static void vibrate(Context ctx){
		try{
			Vibrator vibrator = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE); 
			vibrator.vibrate(new long[]{500,500,1000,1000}, -1);
		}catch(Throwable e){
				UtilLog.e("vibrate: "+e.getMessage());
		}
	}
	
	
	

}
